package com.example.usedcardealer;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class AddCarsActivity extends AppCompatActivity implements View.OnClickListener {
    //组件定义
    private EditText etCjh;
    private EditText etPp;
    private EditText etXh;
    private EditText etLx;

    private Button btnAdd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addcars);
        //初始化界面
        initView();
    }

    //初始化界面
    private void initView() {
        etCjh=(EditText) findViewById(R.id.et_cjh);
        etPp = (EditText) findViewById(R.id.et_pp);
        etXh = (EditText) findViewById(R.id.et_xh);
        etLx = (EditText) findViewById(R.id.et_lx);

        btnAdd = (Button) findViewById(R.id.btn_add);
        //设置按钮的点击事件
        btnAdd.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        //当单击“添加”按钮时，获取添加信息
        String cjh= etCjh.getText().toString().trim();
        String pp = etPp.getText().toString().trim();
        String xh = etXh.getText().toString().trim();
        String lx = etLx.getText().toString();


        //检验信息是否正确
        if (TextUtils.isEmpty(cjh)) {
            Toast.makeText(this, "请输入车架号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(pp)) {
            Toast.makeText(this, "请输入品牌", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(xh)) {
            Toast.makeText(this, "请输入型号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(lx)) {
            Toast.makeText(this, "请输入类型", Toast.LENGTH_SHORT).show();
            return;
        }

        //添加信息
        Car a =new Car();
        a.cjh= cjh;
        a.pp = pp;
        a.xh = xh;
        a.lx= lx;

        //创建数据库访问对象
        CarsDAO dao = new CarsDAO(getApplicationContext());
        //打开数据库
        dao.open();
        //执行数据库访问方法
        long result = dao.addCars(a);

        if (result > 0) {
            Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "添加失败", Toast.LENGTH_SHORT).show();
        }
        //关闭数据库
        dao.close();
        //关闭活动
        finish();

    }
}
